package com.hu.service.impl;

import com.hu.context.BaseContext;
import com.hu.dao.QuestionDao;
import com.hu.entity.dto.GenerateQuestionDto;
import com.hu.entity.dto.UserRegisterDTO;
import com.hu.entity.pojo.QuestionEntity;
import com.hu.entity.pojo.UserEntity;
import com.hu.mapper.QuestionMapper;
import com.hu.mapper.UserMapper;
import com.hu.service.QuestionService;
import jakarta.servlet.http.HttpSession;
import lombok.extern.slf4j.Slf4j;
import org.springframework.ai.chat.client.ChatClient;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.scheduling.annotation.Async;
import org.springframework.scheduling.annotation.AsyncResult;
import org.springframework.stereotype.Service;
import com.alibaba.fastjson.JSON;

import java.time.LocalDateTime;
import java.util.List;
import java.util.concurrent.Future;

@Slf4j
@Service
public class QuestionServiceImpl implements QuestionService {

    @Autowired
    private QuestionDao questionDao;

    @Autowired
    private ChatClient chatClient;

    @Autowired
    private QuestionMapper questionMapper;

    @Autowired
    private UserMapper userMapper;

    @Override
    public boolean saveQuestions(List<QuestionEntity> questionEntities) {
        questionDao.saveAll(questionEntities);
        return true;
    }

    @Override
    @Async // 方法上添加了异步任务方法  那么方法只能返回void 或者future
    public Future<Boolean> generateQuestion(GenerateQuestionDto generateQuestionDto, String uuid,Long userId) {

        // 获取当前用户题目数量
        UserEntity u = new UserEntity();
        u.setId(userId);
        UserEntity user = userMapper.selectUser(u);
        // 判断达到上限没有
        Integer questionNum = user.getQuestionNum();
        Integer questionNum1 = generateQuestionDto.getQuestionNum();
        System.out.println("用户题目数量：" + questionNum + "，此次将要生成的题目数量：" + questionNum1);
        if(user.getQuestionNum() + generateQuestionDto.getQuestionNum() > 50){
            return AsyncResult.forValue(false); // 修改：直接返回AsyncResult结果并终止方法执行
        }
//        log.info("接收到用户的请求：{}", generateQuestionDto.toString());
        String content = chatClient.prompt()
                .system("你是一个精通各行各业的专家，擅长于针对各行各业进行出题，考试，题目 解析等") // 给大模型内置一个角色上去
                                .user("帮我出" + generateQuestionDto.getQuestionNum() + "道" +
                                        generateQuestionDto.getQuestion() + "的题目，" +
                                        generateQuestionDto.getQuestionFormat() )
                                .call().content();

        content = content.replaceAll("```json","").replaceAll("```","");
        System.out.println("大模型返回的内容：" + content);
        // jackson来进行json字符串的反序列化
        /*ObjectMapper objectMapper = new ObjectMapper();
        // 将字符串解析成对象
        List<QuestionEntity> questionEntities = objectMapper.readValue(content,
new TypeReference<List<QuestionEntity>>() {
        });*/
        // fastjson来进行json字符串的反序列化
        List<QuestionEntity> questionEntities = JSON.parseArray(content,
                QuestionEntity.class);
        questionEntities.forEach(item->{item.setGeneratorId(uuid);;
            item.setUserId(userId);
            item.setType(generateQuestionDto.getQuestion());
            item.setCreateTime(LocalDateTime.now());
            item.setIsCollected(0);
            item.setIsWrong(0);
        });


        saveQuestions(questionEntities);
        // 没有到达上限就更新题目数量
        user.setQuestionNum(user.getQuestionNum() + generateQuestionDto.getQuestionNum());
        userMapper.updateUserInfoById(user);
        return AsyncResult.forValue(true);
    }
    @Override
    public List<QuestionEntity> selectByGenerateId(String generateId) {
        List<QuestionEntity> questionEntities =
                questionDao.findQuestionEntitiesByGeneratorId(generateId);
        if (questionEntities == null || questionEntities.isEmpty()) {
            throw new RuntimeException("没有找到对应的题目");
        }
        return questionEntities;
    }

    /**
     * 收藏题目或加入错题集
     */
    public void addCollection(Integer id ,Integer status,Integer operation) {
       if(status == 0){
           // 将题目添加到错题本
           String type = "is_wrong";
           questionMapper.updateStatus(id,type,operation);
       }
       if(status == 1){
           // 将题目添加到收藏夹
           String type = "is_collected";
           questionMapper.updateStatus(id,type,operation);
       }
    }

    /**
     * 根据不同类型查找题目
     * @param status
     * @return
     */
    public List<QuestionEntity> getQuestions(Integer status,Long userId) {
        String type = "";
        // 检查 status 是否为 null，避免后续比较时出现空指针
        if (status != null) {
            if (status == 0) {
                type = "is_wrong"; // 错题标记
            } else if (status == 1) {
                type = "is_collected"; // 收藏标记
            }
            // 其他 status 值默认不设置 type（保持空字符串）
        }
        return questionMapper.getQuestions(userId,type);
    }


    /**
     * 删除题目
     * @param id
     */
    public void deleteQuestion(Integer id, Long userId) {
        // 删除题目
        questionMapper.deleteQuestionById(id);
        // 更新用户题目数量
        userMapper.deleteQuestionNum(userId);
    }
}
